package com.ncs.cns.activity;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.view.KeyEvent;
import android.widget.RadioGroup;
import android.widget.RadioGroup.OnCheckedChangeListener;

import com.ncs.cns.R;
import com.ncs.cns.activity.fragment.AddEventFragment;
import com.ncs.cns.activity.fragment.AllCircuSeeFragment;
import com.ncs.cns.activity.fragment.MyCircuSeeFragment;
import com.ncs.cns.activity.fragment.SettingFragment;
import com.ncs.cns.framework.SysApplication;

public class CircuSeeActivity extends BaseActivity {
	
	private FragmentManager fragManager;
	private RadioGroup radioGroup;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_circu_see);
		
		fragManager = getSupportFragmentManager();
		radioGroup = (RadioGroup)findViewById(R.id.main_tab_group);
		
		radioGroup.setOnCheckedChangeListener(new OnCheckedChangeListener(){
			
			public void onCheckedChanged(RadioGroup group, int checkedId) {
				Fragment fragment = getInstanceByIndex(checkedId);
				fragManager.beginTransaction().replace(R.id.content, fragment).commit();
				
			}
		});
		
		//设置第一次显示的内容
		radioGroup.getChildAt(0).performClick();
		removeTagWithoutId(0);
	}

	private Fragment getInstanceByIndex(int checkedId){
		Fragment fragment = null;		
		switch(checkedId){
		case R.id.bottom_menu_all_topic:
			fragment = new AllCircuSeeFragment();
			radioGroup.getChildAt(0).setTag(true);
			removeTagWithoutId(0);
			break;
			
		case R.id.bottom_menu_my_topic:
			fragment = new MyCircuSeeFragment();
			radioGroup.getChildAt(1).setTag(true);
			removeTagWithoutId(1);
			break;
			
		case R.id.bottom_menu_add_topic:
			fragment = new AddEventFragment();
			radioGroup.getChildAt(2).setTag(true);
			removeTagWithoutId(2);
			break;
		
		case R.id.bottom_menu_setting:
			fragment = new SettingFragment();
			radioGroup.getChildAt(3).setTag(true);
			removeTagWithoutId(3);
			break;
		default :
			fragment = new AllCircuSeeFragment();
			radioGroup.getChildAt(0).setTag(true);
			break;
		}
		return fragment;
	}
	
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK
				&& event.getAction() == KeyEvent.ACTION_DOWN) {
			if ((System.currentTimeMillis() - exitTime) > 2000) {
				showToastShort(R.string.double_click_exit);
				exitTime = System.currentTimeMillis();
			} else {
				SysApplication.getInstance().exit();
			}
			return true;
		}
		return super.onKeyDown(keyCode, event);
	}

	
	public void removeTagWithoutId(int index){
		for(int i =0;i<=3;i++){
			if(i != index)radioGroup.getChildAt(i).setTag(false);
		}
	}
}
